<template>
	<div class="user-info-list-container">
		<Row>
			<Col span="4">
			<Tree :data="areaList" class="tree-data-container" @on-select-change="onSelectChange" />
			</Col>
			<Col span="20">
			<Button type="error" icon="md-add" @click="onAdd" :disabled="selectedArea.nodeLevel !== 4">新增人员</Button>
			<div class="ivu-inline-block ivu-fr">
				<Dropdown @on-click="onChangeTableSize" trigger="click">
					<Tooltip class="ivu-ml" content="密度" placement="top">
						<i-link>
							<Icon type="md-list" />
						</i-link>
					</Tooltip>
					<template #list>
						<DropdownMenu>
							<DropdownItem name="default" :selected="tableSize === 'default'">默认</DropdownItem>
							<DropdownItem name="large" :selected="tableSize === 'large'">宽松</DropdownItem>
							<DropdownItem name="small" :selected="tableSize === 'small'">紧凑</DropdownItem>
						</DropdownMenu>
					</template>
				</Dropdown>
				<Tooltip class="ivu-ml" :content="tableFullscreen ? '退出全屏' : '全屏'" placement="top">
					<i-link @click="onFullscreen">
						<Icon :custom="tableFullscreen ? 'i-icon i-icon-exit-full-screen' : 'i-icon i-icon-full-screen'" />
					</i-link>
				</Tooltip>
				<Tooltip class="ivu-ml" content="刷新" placement="top">
					<i-link @click="onRefresh">
						<Icon custom="i-icon i-icon-refresh" />
					</i-link>
				</Tooltip>
				<Dropdown trigger="click">
					<Tooltip class="ivu-ml" content="列设置" placement="top">
						<i-link>
							<Icon type="md-options" />
						</i-link>
					</Tooltip>
					<template #list>
						<DropdownMenu>
							<div class="ivu-p-8">列展示</div>
							<Divider size="small" class="ivu-mt-8 ivu-mb-8" />
							<li class="ivu-dropdown-item" v-for="item in dropdownColumns" :key="item.title"
								@click="item.show = !item.show">
								<Checkbox v-model="item.show"></Checkbox>
								<span>{{ item.title }}</span>
							</li>
						</DropdownMenu>
					</template>
				</Dropdown>
			</div>
			<Table ref="table" :columns="tableColumns" :data="list" :loading="loading" :size="tableSize" class="ivu-mt">
				<template #action="{ row }">
					<div @click.stop.prevent>
						<Poptip confirm title="您确定删除该人员了吗？" transfer @on-ok="onDelete(row)">
							<a style="color: #ed4014;">删除</a>
						</Poptip>
					</div>
				</template>
			</Table>
			<div class="ivu-mt ivu-text-center">
				<Page :total="total" v-model="pageNum" show-total show-sizer show-elevator :page-size="pageSize"
					@on-change="onChangePage" @on-page-size-change="onChangePageSize" />
			</div>
			</Col>
		</Row>
		<Modal title="新增人员" v-model="visible" @on-cancel="onCancel" class-name="form-modal" :mask-closable="false"
			:width="1000">
			<Row :gutter="8">
				<Col span="11">
				<Table size="small" :columns="userColumns" :data="filteredAllUsers" @on-selection-change="onCheckUserChange" />
				</Col>
				<Col span="2">
				<div class="arrow">
					<Icon type="md-arrow-round-forward" size="24" @click="onConfirmSelect" />
					<Icon type="md-arrow-round-back" size="24" style="margin-top: 10px;" @click="onCancelSelect" />
				</div>
				</Col>
				<Col span="11">
				<Table size="small" :columns="userColumns" :data="selectedUsers" @on-selection-change="onCheckUserChange" />
				</Col>
			</Row>
			<template #footer>
				<Button type="text" @click="onCancel">取消</Button>
				<Button type="primary" @click="onConfirm" :loading="loading">确定</Button>
			</template>
		</Modal>
	</div>
</template>
<script>
import { mapState } from 'vuex'
import { cloneDeep } from 'lodash'
import { getAreaList } from '@/api/common'
import { getUserList } from '@api/user'
import { getUserInfoList, createUserInfo, updateUserInfo } from '@api/user-info'

export default {
	data() {
		return {
			loading: false,
			list: [],
			pageNum: 1,
			pageSize: 10,
			total: 0,
			tableSize: 'small',
			tableFullscreen: false,
			allUsers: [],
			visible: false,
			areaData: [],
			areaList: [],
			selectedArea: {},
			selectingUsers: [],
			selectedUsers: [],
		}
	},
	computed: {
		...mapState('admin/role', [
			'roles'
		]),
		columns() {
			return [
				{ title: '姓名', key: 'userName' },
				{ title: '手机号', key: 'phoneNo' },
				{ title: '所属机房', key: 'roomName' },
				{
					title: '角色',
					key: 'roleCodeList',
					render: (h, { row }) => {
						const roles = row.roleCodeList.map(
							roleCode => (this.roles.find(item => roleCode === item.roleCode) || {}).roleName
						)
						return h('span', roles.join('，') || '/')
					}
				},
				{ title: '值班状态', key: 'status' },
				{ title: '操作', key: 'action', slot: 'action', align: 'center', width: 120, fixed: 'right' }
			]
		},
		tableColumns() {
			const columns = [...this.columns];
			return columns
		},
		dropdownColumns() {
			return this.columns.filter(item => item.title)
		},
		userColumns() {
			return [
				{ type: 'selection', align: 'center', width: 60 },
				{ title: '用户名', key: 'name' },
				{ title: '手机号', key: 'phoneNo' },
				{
					title: '角色',
					key: 'roleCodeList',
					render: (h, { row }) => {
						const roles = row.roleCodeList.map(
							roleCode => (this.roles.find(item => roleCode === item.roleCode) || {}).roleName
						)
						return h('span', roles.join('，') || '/')
					}
				},
			]
		},
		filteredAllUsers() {
			return this.allUsers.filter(item => {
				return !this.selectedUsers.map(i => i.userId).includes(item.userId)
			})
		}
	},
	async mounted() {
		const response = await getAreaList({})
		this.areaData = response
		this.onGenerateTree(response)
	},
	methods: {
		async getAllUsers() {
			const response = await getUserList({
				pageNum: 1,
				pageSize: 1000,
			})
			this.allUsers = response.records || []
		},
		async getData() {
			if (this.loading) return;
			this.loading = true;
			const params = this.$parent.$parent.$refs.form.data;
			const response = await getUserInfoList({
				pageSize: this.pageSize,
				pageNum: this.pageNum,
				keyword: params.keyword || undefined
			})
			this.list = response.records || []
			this.total = response.total;
			this.loading = false;
		},
		onGenerateTree(areaList) {
			const treeData = areaList.filter(area => !area.parentId)
			for (let i = 0; i < treeData.length; i++) {
				treeData[i].expand = true
				treeData[i].children = []
				treeData[i].render = (h, { root, node, data }) => {
					return h('span', {}, data.nodeName)
				}
				cloneDeep(areaList).forEach(area => {
					if (area.parentId === treeData[i].nodeId) {
						if (!area.children) {
							area.expand = true
							area.children = []
							cloneDeep(areaList).forEach(subArea => {
								if (subArea.parentId === area.nodeId) {
									subArea.expand = true
									subArea.children = []
									cloneDeep(areaList).forEach(thirdArea => {
										if (thirdArea.parentId === subArea.id) {
											thirdArea.expand = true
											thirdArea.children = []
											thirdArea.render = (h, { root, node, data }) => {
												return h('span', {
													style: {
														width: '100%'
													}
												}, [
													h('span', {
														style: {
															display: 'inline-block',
															width: '80px',
														}
													}, data.nodeName),
												]);
											}
											subArea.children.push(thirdArea)
										}
									})
									subArea.render = (h, { root, node, data }) => {
										return h('span', {
											style: {
												width: '100%'
											}
										}, [
											h('span', {
												style: {
													display: 'inline-block',
													width: '80px',
												}
											}, data.nodeName),
										]);
									}
									area.children.push(subArea)
								}
							})
						}
						area.render = (h, { root, node, data }) => {
							return h('span', {
								style: {
									width: '100%'
								}
							}, [
								h('span', {
									style: {
										display: 'inline-block',
										width: '80px',
									}
								}, data.nodeName),
							]);
						}
						areaList[i].children.push(area)
					}
				})
			}
			this.areaList = treeData
		},
		onSelectChange(_, selectedArea) {
			this.selectedArea = selectedArea
			this.getData()
		},
		onChangeTableSize(size) {
			this.tableSize = size;
		},
		onFullscreen() {
			this.tableFullscreen = !this.tableFullscreen;
			this.$emit('on-fullscreen', this.tableFullscreen);
		},
		onRefresh() {
			this.getData();
		},
		onChangePage(page) {
			this.pageNum = page;
			this.getData();
		},
		onChangePageSize(size) {
			this.pageNum = 1;
			this.pageSize = size;
			this.getData();
		},
		onSearch() {
			this.pageNum = 1;
			this.getData();
		},
		onAdd() {
			this.getAllUsers()
			this.visible = true
		},
		onCheckUserChange(selection) {
			this.selectingUsers = selection
		},
		onConfirmSelect() {
			this.selectedUsers = [
				...this.selectedUsers,
				...this.selectingUsers
			]
			this.selectingUsers = []
		},
		onCancelSelect() {
			this.selectedUsers = this.selectedUsers.filter(item => {
				return !this.selectingUsers.map(i => i.userId).includes(item.userId)
			})
			this.selectingUsers = []
		},
		onCancel() {
			this.selectedUsers = []
			this.selectingUsers = []
			this.visible = false
		},
		async onConfirm() {
			const parent = this.areaData.find(item => {
				return item.id === this.selectedArea.parentId
			}) || {}
			const params = this.selectedUsers.map(item => {
				return {
					roomId: parent.id,
					roomName: parent.nodeName,
					regionId: this.selectedArea.id,
					regionName: this.selectedArea.nodeName,
					userId: item.userId,
					userName: item.name,
					phoneNo: item.phoneNo,
				}
			})
			const response = await createUserInfo(params)
			if (response.code === 1000) {
				this.onCancel()
				this.onSearch()
			}
		},
		async onDelete(row) {
			const response = await updateUserInfo({
				id: row.id,
				isDelete: 1
			})
			if (response.code === 1000) {
				this.$Message.success('删除成功')
				this.pageNum = 1
				this.getData()
			}
		}
	}
}
</script>
<style lang="less">
.form-modal {
	.ivu-form-item-label {
		width: 100%;
		text-align: left;
	}

	.ivu-date-picker {
		width: 100%;
	}

	.arrow {
		width: 100%;
		height: 100%;
		text-align: center;
		display: flex;
		flex-direction: column;
		justify-content: center;
	}
}
</style>
